<?php

namespace App\Modules\CodeDesigner\DynamicProxyMode;

use Hyperf\Logger\Logger;
use Hyperf\Pool\Connection;

class MysqlProxy
{
    /**
     * @var MysqlPool 支持多个连接池，原因在于mysql有多个连接操作
     */
    private static $pool;

    /** @var Connection */
    protected $connection;

    /**
     * @var string 数据库连接
     */
    protected $db;

    public function __construct(Connection $connection, string $db)
    {
        if ($connection != null) {
            $connection = self::$pool[$db];
        } else {
            $connection = self::$pool->get();
        }
        $this->connection = $connection;
        $this->db = $db;
    }

    public function __call($name, $arguments)
    {
        try {
            return $this->connection->$name(...$arguments);
        } catch (\Exception $exception) {
            self::$pool[$this->db] = self::createMysqlPool($this->db);
            $this->connection = self::$pool[$this->db]->get();
            Logger::error('mysql retry err', ['exception' => $exception]);
            throw $exception;
        }

    }
}